<template>
  <div class="add_enterprise">
    <el-form
      ref="addEnterprise"
      :model="enterpriseForm"
      :rules="enterpriseRules"
      label-width="150px"
      class="demo-ruleForm"
      :inline="true"
      label-position="right"
    >
      <el-card class="box-card">
        <div slot="header" class="clearfix">
          <span class="clearfixText">照片信息</span>
        </div>
        <el-form-item prop="businessLicenseImg" class="picture_style">
          <upload
            :usage-name="'businessLicenseImg'"
            @handleSucces="handleUploadSuccess"
            @handleError="handleUploadError"
          />
          <p class="picture_label">
            <i>*</i>营业执照
          </p>
        </el-form-item>
        <el-form-item prop="transportLicenseImg" class="picture_style">
          <upload
            :usage-name="'transportLicenseImg'"
            @handleSucces="handleUploadSuccess"
            @handleError="handleUploadError"
          />
          <p class="picture_label">
            <i>*</i>道路运输许可证
          </p>
        </el-form-item>
        <el-form-item prop="frontImg" class="picture_style">
          <upload
            :usage-name="'frontImg'"
            @handleSucces="handleUploadSuccess"
            @handleError="handleUploadError"
          />
          <p class="picture_label">
            <i>*</i>法人身份证（正面）
          </p>
        </el-form-item>
        <el-form-item prop="backImg" class="picture_style">
          <upload
            :usage-name="'backImg'"
            @handleSucces="handleUploadSuccess"
            @handleError="handleUploadError"
          />
          <p class="picture_label">
            <i>*</i>法人身份证（反面）
          </p>
        </el-form-item>
      </el-card>
      <el-card class="box-card text_form">
        <div slot="header" class="clearfix">
          <span class="clearfixText">基本信息</span>
        </div>
        <el-form-item label="公司全称" prop="name">
          <el-input v-model="enterpriseForm.name" />
        </el-form-item>
        <el-form-item label="统一社会信用代码" prop="creditCode">
          <el-input v-model="enterpriseForm.creditCode" />
        </el-form-item>
        <el-form-item label="公司法人" prop="legalPerson">
          <el-input v-model="enterpriseForm.legalPerson" />
        </el-form-item>

        <el-form-item label="营业执照有效期" prop="businessLicensePeriod">
          <el-date-picker
            v-model="enterpriseForm.businessLicensePeriod"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          />
        </el-form-item>
        <el-form-item label="道路运输许可证号" prop="transportLicenseNo">
          <el-input
            v-model="enterpriseForm.transportLicenseNo"
            type="text"
            placeholder="请输入内容"
            maxlength="18"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="营业执照有效期类型" prop="businessLicenseType">
          <el-radio-group v-model="enterpriseForm.businessLicenseType">
            <el-radio :label="3" value="PERMANENT">无固定日期</el-radio>
            <el-radio :label="6" value="LONG_TERM">长期有效</el-radio>
            <el-radio :label="9" value="PERMANENT">永久有效</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="法人证件类型" prop="documentType">
          <el-select v-model="enterpriseForm.documentType" placeholder="请选择">
            <el-option
              v-for="item in legalPersonLicenseTypeSelector"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="法人证件号码" prop="legalPersonIdCard">
          <el-input
            v-model="enterpriseForm.legalPersonIdCard"
            type="text"
            placeholder="请输入内容"
            maxlength="18"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="法人证件有效期" prop="legalPersonIdCardPeriod">
          <el-date-picker
            v-model="enterpriseForm.legalPersonIdCardPeriod"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          />
        </el-form-item>
        <el-form-item label="法人手机号" prop="legalPersonMobile">
          <el-input
            v-model="enterpriseForm.legalPersonMobile"
            type="text"
            placeholder="请输入内容"
            maxlength="11"
            show-word-limit
          />
        </el-form-item>
      </el-card>
      <el-card class="box-card text_form">
        <div slot="header" class="clearfix">
          <span class="clearfixText">开通账号信息</span>
        </div>
        <el-form-item label="绑定手机号归属" prop="bindingMobileAffiliation">
          <el-select v-model="enterpriseForm.bindingMobileAffiliation" placeholder="请选择">
            <el-option
              v-for="item in bindingMobileAffiliationSelector"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="联系人姓名" prop="contactName">
          <el-input v-model="enterpriseForm.contactName" />
        </el-form-item>
        <el-form-item label="绑定手机号" prop="bindingMobile">
          <el-input v-model="enterpriseForm.bindingMobile" />
        </el-form-item>
        <el-form-item label="绑定邮箱" prop="bindingMailbox">
          <el-input v-model="enterpriseForm.bindingMailbox" />
        </el-form-item>
        <el-form-item label="合同有效期" prop="contractPeriod">
          <el-date-picker
            v-model="enterpriseForm.contractPeriod"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          />
        </el-form-item>
        <el-form-item label="是否需要开票" prop="isInvoice">
          <el-select v-model="enterpriseForm.isInvoice" placeholder="请选择">
            <el-option
              v-for="item in needInvoiceSelector"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="开票公司" prop="invoiceCompanyId">
          <el-select v-model="enterpriseForm.invoiceCompanyId" placeholder="请选择">
            <el-option
              v-for="item in InvoiceCompanySelector"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
      </el-card>
      <el-card class="box-card text_form">
        <div slot="header" class="clearfix">
          <span class="clearfixText">开户信息</span>
        </div>
        <el-form-item label="开户账号" prop="bankAccount">
          <el-input v-model="enterpriseForm.bankAccount" />
        </el-form-item>
        <el-form-item label="开户银行" prop="bank">
          <el-input v-model="enterpriseForm.bank" />
        </el-form-item>
        <el-form-item label="开户支行" prop="bankBranch">
          <el-input v-model="enterpriseForm.bankBranch" />
        </el-form-item>
      </el-card>
      <el-card class="box-card text_form">
        <div slot="header" class="clearfix">
          <span class="clearfixText">发票信息</span>
        </div>
        <el-form-item label="注册电话" prop="registerMobile">
          <el-input
            v-model="enterpriseForm.registerMobile"
            type="text"
            placeholder="支持座机和手机格式"
            maxlength="13"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="开票费率" prop="invoiceRate">
          <el-input-number v-model="enterpriseForm.invoiceRate" :precision="3" :step="0.001" :max="1" />
        </el-form-item>
        <el-form-item label="公司注册地址省市区" prop="registerPrecinct">
          <el-cascader
            v-model="enterpriseForm.registerPrecinct"
            :options="areaOptions"
            @change="handleAreaSelectChange"
          />
        </el-form-item>
        <el-form-item label="公司注册详细地址" prop="registerAddress">
          <el-input v-model="enterpriseForm.registerAddress" />
        </el-form-item>
      </el-card>
    </el-form>
    <div class="enterpriseBtn">
      <el-button type="primary" size="medium" @click="handleSubmit">提交</el-button>
      <el-button size="medium" @click="handleReset">重置</el-button>
    </div>
  </div>
</template>

<script>
import { validUserPhone } from '@/utils/validate'
import { checkMobile } from '@/api/iam/iamUser'
import * as R from 'ramda'
import {
  selector
} from '@/api/iam/area.js'

import {
  createEnterprise
} from '@/api/tms/enterprise.js'
import { parseTime } from '@/utils'
import upload from '@/components/Upload/index'
export default {
  components: {
    upload
  },
  data() {
    const validateMobile = (rule, value, callback) => {
      if (R.isNil(value) || R.isEmpty(value) || !validUserPhone(value)) {
        callback(new Error('请输入正确的手机号码'))
      } else {
        checkMobile(value).then((response) => {
          if (response.isExist) {
            callback(new Error('手机号码已被注册，请换一个试试。'))
          } else {
            callback()
          }
        })
      }
    }
    const validateImages = (rule, value, callback) => {
      if (!this.enterpriseForm[rule.field]) {
        callback(new Error(rule.message))
      } else {
        callback()
      }
    }
    return {
      areaList: [],
      areaOptions: [],
      needInvoiceSelector: [{ label: '开票', value: 'true' }, { label: '不开票', value: 'false' }],
      legalPersonLicenseTypeSelector: [{ label: '身份证', value: 'IDCARD' }, { label: '护照', value: 'PASSPORT' }],
      bindingMobileAffiliationSelector: [{ label: '法人', value: 'LEGAL_PERSON' }, { label: '联系人', value: 'CONCAT_PERSON' }],
      InvoiceCompanySelector: [{ label: '山西', value: '1' }],
      enterpriseForm: {
        name: '',
        invoiceRate: 0.05
      },
      enterpriseRules: {
        businessLicenseImg: [{ required: true, message: '请上传营业执照照片', validator: validateImages, trigger: 'change' }],
        transportLicenseImg: [{ required: true, message: '请上传道路运输许可证照片', validator: validateImages, trigger: 'change' }],
        frontImg: [{ required: true, message: '身份证正面照片不能为空', validator: validateImages, trigger: 'change' }],
        backImg: [{ required: true, message: '身份证反面照片不能为空', validator: validateImages, trigger: 'change' }],
        name: [
          { required: true, message: '企业名称不能为空', trigger: 'blur' },
          { min: 3, max: 32, message: '长度在 3 到 32 个字符', trigger: 'blur' }
        ],
        creditCode: [{ required: true, message: '统一社会信用代码', trigger: 'blur' }],
        legalPerson: [{ required: true, message: '企业法人名称不能为空', trigger: 'blur' }],
        legalPersonIdCard: [{ required: true, message: '企业法人身份证号不能为空', trigger: 'blur' }],
        legalPersonMobile: [{ required: true, message: '企业法人手机号码不能为空', trigger: 'blur' }, { validator: validateMobile }],
        documentType: [{ required: true, message: '企业法人证件类型不能为空', trigger: 'blur' }],
        legalPersonIdCardPeriod: [{ required: true, message: '企业法人证件有效期', trigger: 'blur' }],
        businessLicensePeriod: [{ required: true, message: '营业执照有效期不能为空', trigger: 'blur' }],
        businessLicenseType: [{ required: true, message: '营业执照类型不能为空', trigger: 'blur' }],
        transportLicenseNo: [{ required: true, message: '道路运输许可证号不能为空', trigger: 'blur' }],
        bindingMobile: [{ required: true, message: '绑定手机号不能为空', trigger: 'blur' }, { validator: validateMobile }],
        bindingMobileAffiliation: [{ required: true, message: '绑定手机号归属不能为空', trigger: 'blur' }],
        bindingMailbox: [{ required: true, message: '绑定邮箱不能为空', trigger: 'blur' }],
        contactName: [{ required: true, message: '联系人不能为空', trigger: 'blur' }],
        isInvoice: [{ required: true, message: '是否开票不能为空', trigger: 'blur' }],
        invoiceCompanyId: [{ required: true, message: '开票公司不能为空', trigger: 'blur' }],
        bankAccount: [{ required: true, message: '开户账号不能为空', trigger: 'blur' }],
        bank: [{ required: true, message: '开户银行不能为空', trigger: 'blur' }],
        bankBranch: [{ required: true, message: '开户银行支行不能为空', trigger: 'blur' }],
        registerMobile: [{ required: true, message: '注册电话不能为空', trigger: 'blur' }],
        registerPrecinct: [{ required: true, message: '注册地址省市区不能为空', trigger: 'blur' }],
        registerAddress: [{ required: true, message: '注册地址不能为空', trigger: 'blur' }],
        invoiceRate: [{ required: true, message: '开票率不能为空', trigger: 'blur' }]
      }
    }
  },
  created() {
    selector().then((response) => {
      this.areaList = response
      const provinceList = this.filterAreaByParentId(100000)
      let provinceArea = {}
      for (let i = 0; i < R.length(provinceList); i++) {
        provinceArea = provinceList[i]
        const cityList = this.filterAreaByParentId(provinceArea.id)
        const provinceChildrenList = []
        for (let j = 0; j < R.length(cityList); j++) {
          const cityArea = cityList[j]
          const districtList = this.filterAreaByParentId(cityArea.id)
          const districtMap = e => { return { value: e.areaName, label: e.areaName } }
          provinceChildrenList.push({ value: cityArea.areaName, label: cityArea.areaName, children: R.map(districtMap, districtList) })
        }
        this.areaOptions.push({ value: provinceArea.areaName, label: provinceArea.areaName, children: provinceChildrenList })
      }
    })
  },
  methods: {
    handleSubmit() {
      this.$refs['addEnterprise'].validate((valid) => {
        if (valid) {
          if (!R.isNil(this.enterpriseForm.businessLicensePeriod) && this.enterpriseForm.businessLicensePeriod.length > 1) {
            this.enterpriseForm.businessLicenseStartTime = parseTime(this.enterpriseForm.businessLicensePeriod[0])
            this.enterpriseForm.businessLicenseEndTime = parseTime(this.enterpriseForm.businessLicensePeriod[1])
          }
          if (!R.isNil(this.enterpriseForm.legalPersonIdCardPeriod) && this.enterpriseForm.legalPersonIdCardPeriod.length > 1) {
            this.enterpriseForm.usefulStartTime = parseTime(this.enterpriseForm.legalPersonIdCardPeriod[0])
            this.enterpriseForm.usefulEndTime = parseTime(this.enterpriseForm.legalPersonIdCardPeriod[1])
          }
          if (!R.isNil(this.enterpriseForm.contractPeriod) && this.enterpriseForm.contractPeriod.length > 1) {
            this.enterpriseForm.contractStartTime = parseTime(this.enterpriseForm.contractPeriod[0])
            this.enterpriseForm.contractEndTime = parseTime(this.enterpriseForm.contractPeriod[1])
          }
          if (!R.isNil(this.enterpriseForm.registerPrecinct) && this.enterpriseForm.registerPrecinct.length > 1) {
            this.enterpriseForm.registerProvince = this.enterpriseForm.registerPrecinct[0]
            this.enterpriseForm.registerCity = this.enterpriseForm.registerPrecinct[1]
            this.enterpriseForm.registerDistrict = this.enterpriseForm.registerPrecinct[2]
          }
          createEnterprise(this.enterpriseForm).then(() => {
            this.$notify({
              title: '成功',
              message: '添加成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleAreaSelectChange() {
    },
    filterAreaByParentId(pid) {
      const filter = x => x.areaParentId === pid
      return R.filter(filter, this.areaList)
    },
    handleUploadSuccess(response) {
      this.usageName = response.usageName
      this.enterpriseForm[this.usageName] = response.url
      this.$refs.addEnterprise.validateField(this.usageName)
    },
    handleUploadError(res) {

    },
    handleReset() {
      this.enterpriseForm = {
        invoiceRate: 0.05
      }
    }
  }
}

</script>

<style lang='scss'>
.add_enterprise {
  .demo-ruleForm {
    width: 100%;
    display: flex;
    justify-content: center;
    flex-wrap: wrap;
    .picture_style {
      margin-left: 30px;
      .picture_label {
        text-align: center;
        i {
          color: red;
          margin-right: 5px;
        }
      }
    }
    .text_form {
      .el-form-item {
        margin-left: 120px;
        .el-form-item__content {
          width: 400px;
        }
      }
    }
  }
  .text {
    font-size: 14px;
  }

  .item {
    margin-bottom: 18px;
  }

  .clearfix:before,
  .clearfix:after {
    display: table;
    content: "";
  }
  .clearfix:after {
    clear: both;
  }

  .box-card {
    width: 95%;
    margin-top: 20px;
    .el-card__header {
      padding: 20px 10px 5px 10px;
      border-bottom: 0;
      .clearfix {
        .clearfixText {
          border-left: 2px solid #1890ff;
          padding-left: 10px;
          font-weight: 700;
        }
      }
    }
  }
  .enterpriseBtn {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 60px;
    margin-top: 60px;
    margin-bottom: 60px;
    button {
      margin-left: 30px;
    }
  }
}
</style>
